package com.hmdp.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
//        设置key的前缀
    public static final String KEY_PREFIX = "lock:";

    @Resource
    StringRedisTemplate stringRedisTemplate;
    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeout) {
        long threadID = Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, Long.toString(threadID), timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
//        防止锁进行误删的情况，需要先进行判断 是否为当前线程
//        获取当前线程id
        long currentID = Thread.currentThread().getId();
        String current = Long.toString(currentID);
        String redisThred = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (current.equals(redisThred))
        {
            stringRedisTemplate.delete(KEY_PREFIX+name);
        }

    }
}
